
#@Author: linjinkun
#@Date: 2019-09-05 09:49:44
#@Last Modified by:   linjinkun
#@Last Modified time: 2019-09-05 09:49:44
 
from ...pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.mongo_bill_service import MongoBillFilter
from enum import Enum
from datetime import datetime
from ...service.display.display_ye import DisplayService
from ...service.buss_pub.personnel_organizational import UserType
from server.pao_python.pao.service.security.security_utility import SecurityConstant,get_current_account_id


class relactionship(Enum):
    worker = '雇佣'
class QualificationType(Enum):
    education = '学历证明'
    qualification = '服务资质证明'
    ability = '行为能力'
class ExamResult(Enum):
    high = '偏高'
class DisplayShowService(DisplayService):
    bus_area = '南海'  # 业务区域为南海
    business_area_collection = 'PT_Business_Area'  # 业务区划表名
    current_year = 2019  #当前年份
    user_id = '0ab506ba-cfd9-11e9-8086-144f8aec0be5'
    '''测试服务'''
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd,inital_password,session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
    
    
    ####################  机构养老-明细     #####################
    def org_detail_sex_quantity(self, condition, page, count):
        '''机构养老-明细-长者数量-性别'''
        table_name = 'PT_Hotel_Zone'
        _filter = self.__get_elder_filter(condition)
        _filter.group({'x': '$user.personnel_info.sex'}, [{'y': self.ao.summation(1)}])
        res = self.__get_data(_filter,table_name)
        return res
    
    def org_detail_age_quantity(self, condition, page, count):
        '''机构养老-明细-长者数量-年龄'''
        table_name = 'PT_Hotel_Zone'
        curYear = datetime.now().year
        _filter = self.__get_elder_filter(condition)
        _filter.add_fields({'year': self.ao.year('$user.personnel_info.date_birth')})
        _filter = self.__elder_group_by_age(_filter)
        _filter.group({'x':'$age_range'},[{'y':self.ao.summation(1)}])\
            .sort({'x':1})
        res = self.__get_data(_filter,table_name)
        return res
    
    def org_detail_education_quantity(self, condition, page, count):
        '''机构养老-明细-长者数量-学历'''
        table_name = 'PT_Hotel_Zone'
        _filter = self.__get_elder_filter(condition)
        _filter.unwind('user.qualification_info')\
               .inner_join_bill('PT_Qualification_Type', 'user.qualification_info.qualification_type_id', 'id', 'qualification_type_info')\
               .match(C('qualification_type_info.name') == '学历证明')\
               .group({'x': '$user.qualification_info.name'}, [{'y': self.ao.summation(1)}])
        res = self.query(_filter, table_name)
        return res
    
    def org_detail_ability_quantity(self, condition, page, count):
        '''机构养老-明细-长者数量-行为能力'''
        table_name = 'PT_Hotel_Zone'
        _filter = self.__get_elder_filter(condition)
        _filter.unwind('user.qualification_info')\
               .inner_join_bill('PT_Qualification_Type', 'user.qualification_info.qualification_type_id', 'id', 'qualification_type_info')\
               .match(C('qualification_type_info.name') == '行为能力')\
               .group({'x': '$user.qualification_info.name'}, [{'y': self.ao.summation(1)}])
        res = self.query(_filter, table_name)
        return res

    def org_statistics_identity_affiliation_personnel_quantity(self, condition, page, count):
        '''机构养老-明细-长者数量-所属身份'''
        _filter = self.__eld_area_basic()
        _filter.inner_join_bill('PT_Social_Groups_Type', 'user_info.personnel_info.social_groups_type_id', 'id', 'social_type')\
               .group({'x': '$social_type.name'}, [{'y': self.ao.summation(1)}])
        res = self.query(_filter, self.business_area_collection)
        return res

    def org_detail_sex_personnel_quantity(self, condition, page, count):
        '''机构养老-明细-工作人员数量-性别'''
        table_name = 'PT_User_Relationship'
        _filter = self.__get_worker_filter(condition)
        _filter.group({'x': '$user.personnel_info.sex'}, [{'y': self.ao.summation(1)}])
        res = self.__get_data(_filter,table_name)
        return res

    def org_detail_age_personnel_quantity(self, condition, page, count):
        '''机构养老-明细-工作人员数量-年龄'''
        table_name = 'PT_User_Relationship'
        curYear = datetime.now().year
        _filter = self.__get_worker_filter(condition)
        _filter.add_fields({'year': self.ao.year('$user.personnel_info.date_birth')})
        _filter = self.__worker_group_by_age(_filter)
        _filter.group({'x':'$age_range'},[{'y':self.ao.summation(1)}])\
               .sort({'x':1})
        res = self.__get_data(_filter,table_name)
        return res
    
    def org_detail_education_personnel_quantity(self, condition, page, count):
        '''机构养老-明细-工作人员数量-学历'''
        table_name = 'PT_User_Relationship'
        _filter = self.__get_worker_filter(condition)
        _filter.unwind('user.qualification_info')\
               .inner_join_bill('PT_Qualification_Type', 'user.qualification_info.qualification_type_id', 'id', 'qualification_type_info')\
               .match(C('qualification_type_info.name') == '学历证明')\
               .group({'x': '$user.qualification_info.name'}, [{'y': self.ao.summation(1)}])
        res = self.query(_filter, table_name)
        return res

    def org_detail_qualifications_personnel_quantity(self, condition, page, count):
        '''机构养老-明细-工作人员数量-服务资质证明'''
        table_name = 'PT_User_Relationship'
        _filter = self.__get_worker_filter(condition)
        _filter.unwind('user.qualification_info')\
               .inner_join_bill('PT_Qualification_Type', 'user.qualification_info.qualification_type_id', 'id', 'qualification_type_info')\
               .match(C('qualification_type_info.name') == QualificationType.qualification.value)\
               .group({'x': '$user.qualification_info.name'}, [{'y': self.ao.summation(1)}])
        res = self.query(_filter, table_name)
        return res
    
    def org_statistics_qualifications_personnel_quantity(self, condition, page, count):
        _filter = self.__org_area()
        _filter.unwind('user_info.qualification_info')\
               .inner_join_bill('PT_Qualification_Type', 'user_info.qualification_info.qualification_type_id', 'id', 'qualification_type_info')\
               .match(C('qualification_type_info.name') == QualificationType.qualification.value)\
               .group({'x': '$user_info.qualification_info.name'}, [{'y': self.ao.summation(1)}])
        res = self.query(_filter, self.business_area_collection)
        return res
        

    def org_statistics_health_indicators_personnel_quantity(self, condition, page, count):
        '''养老机构-长者数量-健康指标'''
        _filter = self.__eld_area_basic()
        _filter.inner_join_bill('PT_Physical_Exam_Record', 'user_info.id', 'user_id', 'exam_recode') \
                .add_fields({'exam_result':'$exam_recode.physical_exam_data'})\
                .unwind('exam_result')\
                .match(C('exam_result.result') == ExamResult.high.value) \
                .group({'x':'$exam_result.data_item','y':self.ao.summation(1)})\
                .project({'_id': 0, 'exam_recode._id': 0})
        res = self.query(_filter, self.business_area_collection)
        return res

    # def org_statistics_children_personnel_quantity(self, condition, page, count):
    #     '''养老机构-长者数量-子女情况'''        
    #     table_name = 'PT_Hotel_Zone'
    #     _filter = self.__get_elder_filter(condition)
    #     _filter.inner_join_bill('PT_User_Relationship', 'user_info.id', 'main_relation_people', 'relation_info')\
    #            .inner_join_bill('PT_User_Relationship_Type', 'relation_info.relationship_type_id', 'id', 'relation_type_info')\
    #            .match(C('relation_type_info.name') == '子女') \
    #            .group({''})
    #         #    .group({'x': '$user_info.name'}, [{'y': self.ao.summation(1)}])
    #     res = self.query(_filter, table_name)
    #     return res


    def org_detail_post_personnel_quantity(self, condition, page, count):
        '''机构养老-明细-工作人员数量-岗位'''
        table_name = 'PT_User_Relationship'
        _filter = self.__get_worker_filter(condition)
        _filter.group({'x': '$sub_type'}, [{'y': self.ao.summation(1)}])
        res = self.query(_filter,table_name)
        return res

    def org_detail_live_bed_quantity(self,condition,page,count):
        '''机构养老-明细-床位数量'''
        table_name = 'PT_Hotel_Zone'
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match_bill(C('organization_id') == oragnization_id)\
                .inner_join_bill('PT_Bed', 'id', 'area_id', 'bed')\
                .add_fields({'state':self.ao.switch([self.ao.case(F('bed.residents_id') != '','入住')],'空住')})\
                .group({'x': '$state'}, [{'y': self.ao.summation(1)}])
        res = self.__get_data(_filter,table_name)
        return res
    
    def org_detail_time_live_quantity(self,paramValues):
        '''机构养老-明细-入住人数走势'''
        table_name = 'IEC_Check_In'
        start_date = as_date(paramValues['start_date'])
        end_date = as_date(paramValues['end_date'])
        _filter = MongoBillFilter()
        _filter.match_bill((C('create_date') > start_date) & (C('create_date') < end_date))\
                .add_fields({'date': self.ao.date_to_string('$create_date', "%Y-%m-%d")})\
                .group({'x': '$date'}, [{'y': self.ao.summation(1)}])
        res = self.page_query(_filter, table_name, None, None)
        return res
        
    def org_detail_time_line_up_quantity(self,paramValues):
        '''机构养老-明细-预约入住人数走势'''
        table_name = 'PT_Reservation_Registration'
        start_date = as_date(paramValues['start_date'])
        end_date = as_date(paramValues['end_date'])
        _filter = MongoBillFilter()
        _filter.match_bill((C('create_date') > start_date) & (C('create_date') < end_date))\
                .add_fields({'date': self.ao.date_to_string('$create_date', "%Y-%m-%d")})\
                .group({'x': '$date'}, [{'y': self.ao.summation(1)}])
        res = self.page_query(_filter, table_name, None, None)
        return res
        
    # def org_detail_service_count(self):
    #     '''机构养老-明细-总服务次数'''
    #     table_name = 'PT_User_Relationship'
    #     _filter = self.__get_bed_filter(condition)
    #     _filter.inner_join_bill({'IEC_Check_In', 'bed.id', 'bed_id', 'checkin'}) \
    #            .inner_join_bill({'PT_Service_Record', 'checkin.order_id', 'order_id', 'recode'})\
    #            .count('y')
    #     res = self.__get_data(_filter, table_name)
    #     return res

    # def org_detail_service_elder_count(self):
    #     '''机构养老-明细-总服务人数'''
    #     table_name = 'PT_User_Relationship'
    #     _filter = self.__get_bed_filter(condition)
    #     _filter.inner_join_bill({'IEC_Check_In', 'bed.id', 'bed_id', 'checkin'}) \
    #             .count('y')
    #     res = self.__get_data(_filter, table_name)
    #     return res

    # def org_detail_service_cost(self):
    #     '''机构养老-明细-总服务收益'''
    #     table_name = 'PT_User_Relationship'
    #     _filter = self.__get_bed_filter(condition)
    #     _filter.inner_join_bill({'IEC_Check_In', 'bed.id', 'bed_id', 'checkin'}) \
    #            .inner_join_bill({'PT_Service_Record', 'checkin.order_id', 'order_id', 'recode'}) \
    #            .group(None, [{'x': self.ao.summation('$recode.valuation_amount')}])
    #     res = self.__get_data(_filter, table_name)
    #     return res

    def org_detail_video_surveillance(self,condition,page,count):
        '''机构养老-明细-视频监控'''
        _filter = MongoBillFilter()
        oragnization_id = self.__get_organization(condition)
        _filter.match_bill(C('link_obj_id') == oragnization_id) \
                .project({'_id':0,'x':'$url','y':'$title'})
        res = self.query(_filter, 'PT_Monitor')
        return res

    def org_detail_total_quantity(self,condition,page,count):
        '''机构养老-明细-工作人员总数'''
        _filter = self.__get_worker_filter(condition)
        _filter.count('y')
        res = self.query(_filter, 'PT_User_Relationship')
        '''机构养老-明细-床位总数'''
        table_name = 'PT_Hotel_Zone'
        _filter2 = self.__get_bed_filter(condition)
        _filter2.count('y')
        res = res+ self.query(_filter2, table_name)
        '''机构养老-明细-入住长者数量'''
        table_name = 'PT_Hotel_Zone'
        _filter3 = self.__get_elder_filter(condition)
        _filter3.count('y')
        res = res+ self.query(_filter3,table_name)
        return res

    def org_detail_bed_quantity(self,condition,page,count):
        '''机构养老-明细-床位总数'''
        table_name = 'PT_Hotel_Zone'
        _filter = self.__get_bed_filter(condition)
        _filter.count('y')
        res = self.__get_data(_filter, table_name)
        return res

    def org_detail_elder_quantity(self,condition,page,count):
        '''机构养老-明细-入住长者数量'''
        table_name = 'PT_Hotel_Zone'
        _filter = self.__get_elder_filter(condition)
        _filter.count('y')
        res = self.__get_data(_filter,table_name)
        return res

    def org_detail_welfare_centre(self,condition,page,count):
        '''机构养老-明细-福利院简介'''
        table_name = 'PT_User'
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == oragnization_id)\
               .project({'_id':0,'y1':'$name','y2':'$address','x':'$content','y4':'$organization_info.personnel_category','y5':'$organization_info.organization_nature','y6':'$organization_info.legal_person','y7':'$organization_info.telephone'})
        res = self.query(_filter, table_name)
        return res
        
    def org_detail_picture_list(self,condition,page,count):
        '''机构养老-明细-图片列表'''        
        table_name = 'PT_Multi_Media'
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match(C('link_obj_id') == oragnization_id)\
                .project({'_id':0,'y':'$content_url'})
        res = self.__get_data(_filter, table_name)
        res_list = self.___create_list(res)
        return res_list
    
    def org_detail_activity_picture_list(self,condition,page,count):
        '''机构养老-明细-活动图片列表'''
        table_name = 'PT_Activity'
        _filter = self.__get_activity_filter(condition)
        _filter.project({'_id':0,'y':'$photo'})
        res = self.query(_filter, table_name)
        if res:
            res_list = res[0].get('y')
            return res_list
        else:
            return []

    def org_detail_personal_list(self, condition,page,count):
        '''机构养老-明细-人员风采轮播列表'''
        # 模拟
        table_name = 'PT_User_Relationship'
        _filter = self.__get_worker_filter(condition)
        _filter.project({'_id':0,'x':'$user.personnel_info.photo','y2':'$user.qualification_info.name','y1':'$user.content','y3':'$user.name'})
        res = self.__get_data(_filter, table_name)
        return res

    def org_detail_service_products(self, condition,page,count):
        '''机构养老-明细-服务产品介绍轮播'''
        table_name = 'PT_Service_Product'
        _filter = MongoBillFilter()
        _filter.match_bill((C('org_id') == condition['id']) & (C('state') == '1')) \
               .project({'_id': 0, 'y1': '$name', 'x': '$picture_collection', 'y2':'$introduce'})
        res = self.query(_filter, table_name)
        return res
        
    def org_detail_service_products_list(self,condition,page,count):
        '''机构养老-明细-服务产品清单'''
        table_name = 'PT_Service_Product'
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match_bill((C('org_id') == oragnization_id) & (C('state') == '1'))\
               .project({'_id': 0, 'y1': '$name', 'x': '$picture_collection', 'y2':'$introduce'})
        res = self.query(_filter, table_name)
        if res:
            for result in res:
                if result.get('x'):
                    result['x'] = result.get('x')[0]
                else:
                    result['x'] = 'https://image.baidu.com/search/detail?ct=503316480&z=&tn=baiduimagedetail&ipn=d&word=%E6%9A%82%E6%97%A0%E5%9B%BE%E7%89%87%E7%9A%84%E5%9B%BE%E7%89%87&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=-1&hd=&latest=&copyright=&cs=3885376987,415548851&os=2731255382,2303100907&simid=3581205336,620720692&pn=1&rn=1&di=37760&ln=740&fr=&fmq=1568689952123_R&ic=&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&is=0,0&istype=2&ist=&jit=&bdtype=11&spn=0&pi=0&gsm=0&hs=2&objurl=http%3A%2F%2Ffs.zhenjiang365.cn%2Fbbsimg%2Ffcmb%2Fimage%2Fnopic590.jpg&rpstart=0&rpnum=0&adpicid=0&force=undefined'
        return res

    def org_detail_newst_activity(self,condition):
        '''机构养老-明细-最新活动情况'''
        table_name = 'PT_Activity'
        _filter = self.__get_activity_filter(condition)
        _filter.sort({'begin_date': -1})\
               .limit(1)\
               .lookup_bill('PT_Activity_Participate', 'id', 'activity_id', 'participate')\
               .add_fields({'count':self.ao.size('participate')})
        res = self.__get_data(_filter, table_name)
        return res
    def org_detail_service_price_picture(self, condition, page, count):
        '''机构养老-明细-价格表'''
        table_name = 'PT_Multi_Media'
        _filter = MongoBillFilter()
        _filter.match((C('link_obj_id') == condition['id']) & (C('classification') == '服务价格表')) \
               .project({'_id': 0, 'y': '$content_url'})
        res = self.query(_filter, table_name)
        res_list = self.___create_list(res)
        return res_list
        
    ######## 综合统计 start #########
    def cop_statistics_elder_age_fee_quantity(self,condition,page,count):
        '''按年龄分组统计服务费用'''
        _filter_elder = self.__eld_area_basic()
        _filter_elder.add_fields({'age_range': self.__get_age_range()})
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_amount = self.__group_amount_by_age(_filter_recode)
        res = self.__get_data(_filter_amount, self.business_area_collection)
        return res

    def eld_statistics_ability_elder_quantity(self, condition, page, count):
        '''统计-按行为能力统计长者'''
        _filter = self.__eld_area_basic()
        _filter.unwind('user_info.qualification_info')\
               .inner_join_bill('PT_Qualification_Type', 'user_info.qualification_info.qualification_type_id', 'id', 'qualification_type_info')\
               .match(C('qualification_type_info.name') == QualificationType.ability.value)\
               .group({'x': '$user_info.qualification_info.name'}, [{'y': self.ao.summation(1)}])
        res = self.query(_filter, self.business_area_collection)
        return res

    def cop_statistics_service_personal_evaluate_top12_quantity(self, condition, page, count):
        ''' 按评价分数统计top10的服务人员'''
        return self.spe_statistics_service_personal_evaluate_quantity(condition, page, count)

    def cop_statistics_elder_evaluate_top13_quantity(self, condition, page, count):
        '''按服务评分统计top10的长者'''
        _filter_elder = self.__eld_area_basic()
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_service = self.__get_service_score_top10_quantity(_filter_recode)
        res = self.query(_filter_service, self.business_area_collection)
        return res
    
    def cop_statistics_age_evaluate_quantity(self, condition, page, count):
        '''按长者年龄段分组统计评分'''
        _filter_elder = self.__eld_area_basic()
        _filter_elder.add_fields({'age_range': self.__get_age_range()})
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_score = self.__get_service_score_top10_by_age(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res
        
    def cop_statistics_street_evaluate_quantity(self, condition, page, count):
        '''按街镇统计服务评价次数'''
        _filter_elder = self.__eld_area_basic()
        _filter_elder.add_fields({"town":'$user_info.town'})
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_score = self.__get_service_evaluate_top10_by_twon(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def cop_statistics_item_top10_quantity(self, condition, page, count):
        ''' 按服务项目统计服务次数 '''
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_recode.group({'x': '$item.name', 'id': '$record_info.item_id'}, [{'y': self.ao.summation(1)}]) \
                      .project({'x': 1, 'y': 1})
        res = self.query(_filter_recode,self.business_area_collection)
        return res

    def cop_statistics_org_top10_quantity(self, condition, page, count):
        '''按组织机构统计服务次数'''
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_recode.group({'x': '$user_info.name', 'id': '$user_info.id'}, [{'y': self.ao.summation(1)}]) \
                      .project({'x': 1, 'y': 1})
        res = self.query(_filter_recode,self.business_area_collection)
        return res

    def cop_statistics_elder_type_evaluate_quantity(self,condition,page,count):
        '''按长者类型统计服务评价次数'''
        _filter_elder = self.__eld_area_basic()
        _filter_elder.inner_join_bill('PT_Social_Groups_Type', 'user_info.personnel_info.social_groups_type_id', 'id', 'social_type')
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_twon = self.__get_service_evaluate_top10_by_type(_filter_recode)
        res = self.query(_filter_twon, self.business_area_collection)
        return res

    def cop_statistics_fee_total_quantity(self, condition, page, count):
        '''统计总费用'''
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_amount = self.__get_amount_all(_filter_recode)
        res = self.query(_filter_amount, self.business_area_collection)
        return res

    def cop_statistics_total_quantity(self, condition, page, count):
        '''统计总次数'''
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_count = self.__get_evaluate_count_all(_filter_recode)
        res = self.query(_filter_count, self.business_area_collection)
        return res

    def cop_statistics_service_personal_top10_quantity(self, condition, page, count):
        ''' 统计服务人员的服务次数（TOP10）'''
        return self.spe_statistics_service_personal_top10_quantity(condition, page, count)

    def cop_statistics_elder_top10_quantity(self, condition, page, count):
        ''' 统计长者的服务次数 '''
        _filter_elder = self.__eld_area_basic()
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_count = self.__get_service_count_top10_quantity(_filter_recode)
        res = self.query(_filter_count,self.business_area_collection)
        return res

    def cop_statistics_elder_age_quantity(self, condition, page, count):
        ''' 按长者年龄统计服务次数 '''
        _filter_elder = self.__eld_area_basic()
        _filter_age = self.__fiter_age(_filter_elder)
        _filter_recode = self.__get_elder_recode_by_order(_filter_age)
        _filter_count = self.__get_service_count_by_age(_filter_recode)
        res = self.query(_filter_count,self.business_area_collection)
        return res

    def cop_statistics_street_quantity(self, conditon, page, count):
        '''按街镇统计服务次数'''
        _filter_elder = self.__eld_area_basic()
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_twon = self.__group_by_town(_filter_recode)
        res = self.query(_filter_twon,self.business_area_collection)
        return res

    def cop_statistics_item_fee_top10_quantity(self, condition, page, count):
        ''' 按服务项目统计服务费用 '''
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_amount = self.__get_amount_by_item(_filter_recode)
        res = self.query(_filter_amount,self.business_area_collection)
        return res

    def cop_statistics_org_fee_top10_quantity(self, condition, page, count):
        ''' 按服务机构统计服务费用top10 '''
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_amount = self.__group_amount_by_person_top10(_filter_recode)
        res = self.query(_filter_amount, self.business_area_collection)
        return res

    def cop_statistics_service_personal_fee_top10_quantity(self, condition, page, count):
        '''按服务人员统计服务费用top10'''
        return self.spe_statistics_service_personal_income_top10_quantity(condition, page, count)

    def cop_statistics_elder_fee_top10_quantity(self, condition, page, count):
        '''按长者统计服务费用'''
        _filter_elder = self.__eld_area_basic()
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_amount = self.__group_amount_by_person_top10(_filter_recode)
        res = self.query(_filter_amount, self.business_area_collection)
        return res

    def cop_statistics_org_evaluate_top11_quantity(self, condition, page, count):
        '''按服务机构统计服务评分'''
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_score = self.__get_service_score_top10_quantity(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def cop_statistics_street_fee_quantity(self, condition, page, count):
        '''按街镇统计服务评分'''
        _filter_elder = self.__eld_area_basic()
        _filter_elder.add_fields({"town":'$user_info.town'})
        # _filter_elder = self.__filter_twon(_filter_elder)
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_score = self.__get_service_amount_top10_by_twon(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def cop_statistics_elder_type_fee_quantity(self, condition, page, count):
        _filter = self.__eld_area_basic()
        _filter.inner_join_bill('PT_Social_Groups_Type', 'user_info.personnel_info.social_groups_type_id', 'id', 'social_type')
        _filter_recode = self.__get_elder_recode_by_order(_filter)
        _filter_score = self.__get_service_amount_top10_by_type(_filter_recode)
        res = self.query(_filter, self.business_area_collection)
        return res

    def cop_statistics_item_evaluate_top10_quantity(self, condition, page, count):
        '''按服务项目统计服务评分'''
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_score = self.__get_evaluate_count_by_item(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def cop_statistics_evaluate_quantity(self, condition, page, count):
        _filter_user = self.__org_area()
        _filter_recode = self.__get_service_recode_by_organization(_filter_user)
        _filter_score = self.__get_evaluate_count_all(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    ######## 综合统计 end #########






    ######## 服务人员 #########
    def spe_statistics_welfare_centre_quantity(self,condition, page, count):
        '''服务人员-统计-福利院服务人员总人数'''
        return self.org_statistics_service_personal_total_quantity(condition, page, count)

    def spe_statistics_total_quantity(self,condition, page, count):
        '''服务人员-统计-服务人员总人数'''
        _filter = self.__get_all_service_person_all()
        _filter.count('y')
        res = self.__get_data(_filter, self.business_area_collection)
        res2 = self.spe_statistics_welfare_centre_quantity(condition, page, count)
        res3 = self.spe_statistics_community_personal_quantity(condition, page, count)
        if res2:
            res.append({'y':res2[0]['y']})
        else:
            res.extend({'y':0})
        if res3:
            res.extend(res3)
        else:
            res.extend({'y':0})
        return res

    def spe_statistics_community_personal_quantity(self,condition, page, count):
       '''服务人员-统计-社区服务人员总人数'''
       _filter = self.__org_area_community_service_person()
       _filter.count('y')
       res = self.__get_data(_filter, self.business_area_collection)
       return res
    
    def spe_statistics_education_service_personal_quantity(self,condition, page, count):
        '''服务人员-统计-社区服务人员人数-学历'''
        _filter = self.__org_area_community_service_person()
        _filter_education = self.__group_by_education(_filter)
        res = self.query(_filter_education,self.business_area_collection)
        return res

    def spe_statistics_sex_service_personal_quantity(self,condition, page, count):
        '''服务人员-统计-社区服务人员人数-性别'''
        _filter = self.__org_area_community_service_person()
        _filter_education = self.__group_by_sex(_filter)
        res = self.query(_filter_education,self.business_area_collection)
        return res
    
    def spe_statistics_age_service_personal_quantity(self,condition, page, count):
        '''服务人员-统计-社区服务人员人数-年龄'''
        _filter = self.__org_area_community_service_person()
        # _filter = self.__worker_group_by_age(_filter)
        _filter_education = self.__group_by_age(_filter,'worker')
        res = self.query(_filter_education,self.business_area_collection)
        return res

    def spe_statistics_org_service_personal_quantity(self,condition, page, count):
        '''服务人员-统计-社区服务人员人数-机构'''
        _filter = self.__org_area_community_service_person()
        _filter = self.__group_by_organization(_filter)
        res = self.query(_filter, self.business_area_collection)
        return res
        

    def spe_statistics_community_quantity(self,condition, page, count):
        '''服务人员-统计-社区服务人员人数-街镇'''
        _filter = self.__org_area_community_service_person()
        _filter = self.__group_by_town(_filter)
        res = self.query(_filter, self.business_area_collection)
        return res

    def spe_statistics_service_personal_evaluate_quantity(self,condition, page, count):
        '''服务人员-统计-服务评价（TOP10）'''
        _filter = self.__get_all_service_person_all()
        _filter_recode = self.__get_service_recode_by_servicer(_filter)
        _filter_score = self.__get_service_score_top10_quantity(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def spe_statistics_education_evaluate_quantity(self,condition, page, count):
        '''服务人员-统计-服务评价（TOP10）by学历'''
        _filter = self.__get_all_service_person_all()
        _filter_education = self.__filter_education(_filter)
        _filter_recode = self.__get_service_recode_by_servicer(_filter_education)
        _filter_score = self.__get_service_score_top10_by_education(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def spe_statistics_sex_evaluate_quantity(self,condition, page, count):
        '''服务人员-统计-服务评价（TOP10）by性别'''
        _filter = self.__get_all_service_person_all()
        _filter_recode = self.__get_service_recode_by_servicer(_filter)
        _filter_score = self.__get_service_score_top10_by_sex(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res
    
    def spe_statistics_age_evaluate_quantity(self,condition, page, count):
        '''服务人员-统计-服务评价（TOP10）by年龄'''
        _filter = self.__get_all_service_person_all()
        _filter.add_fields({'year': self.ao.year('$user_info.personnel_info.date_birth')})
        _filter_age = self.__worker_group_by_age(_filter)
        _filter_recode = self.__get_service_recode_by_servicer(_filter_age)
        _filter_score = self.__get_service_score_top10_by_age(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def spe_statistics_service_personal_top10_quantity(self,condition, page, count):
        '''服务人员-统计-服务次数（TOP10)'''
        _filter = self.__get_all_service_person_all()
        _filter_recode = self.__get_service_recode_by_servicer(_filter)
        _filter_score = self.__get_service_count_top10_quantity(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def cop_statistics_elder_type_quantity(self, condition, page, count):
        '''按长者类型统计服务次数'''
        _filter_elder = self.__eld_area_basic()
        _filter_elder.inner_join_bill('PT_Social_Groups_Type', 'user_info.personnel_info.social_groups_type_id', 'id', 'social_type')
        _filter_recode = self.__get_elder_recode_by_order(_filter_elder)
        _filter_twon = self.__get_service_count_top10_by_type(_filter_recode)
        res = self.query(_filter_twon,self.business_area_collection)
        return res
        

    def spe_statistics_education_quantity(self,condition, page, count):
        '''服务人员-统计-服务次数 by 学历'''
        _filter = self.__get_all_service_person_all()
        _filter_education = self.__filter_education(_filter)
        _filter_recode = self.__get_service_recode_by_servicer(_filter_education)
        _filter_score = self.__get_service_count_by_education(_filter_recode)
        print('>>>>>>>>>>>>>>>>>>>>>',_filter.filter_objects)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def spe_statistics_age_quantity(self,condition, page, count):
        '''服务人员-统计-服务次数 by 年龄'''
        _filter = self.__get_all_service_person_all()
        _filter.add_fields({'year':self.ao.year('$user_info.personnel_info.date_birth')})
        _filter = self.__worker_group_by_age(_filter)
        _filter_recode = self.__get_service_recode_by_servicer(_filter)
        _filter_score = self.__get_service_count_by_age(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def spe_statistics_sex_quantity(self,condition, page, count):
        '''服务人员-统计-服务次数 by 性别'''
        _filter = self.__get_all_service_person_all()
        _filter_recode = self.__get_service_recode_by_servicer(_filter)
        _filter_score = self.__get_service_count_by_sex(_filter_recode)
        res = self.query(_filter_score, self.business_area_collection)
        return res

    def spe_statistics_service_personal_income_top10_quantity(self,condition, page, count):
        '''服务人员-统计-服务收入（TOP10）'''
        _filter = self.__get_all_service_person_all()
        _filter_recode = self.__get_service_recode_by_servicer(_filter)
        _filter_amount = self.__group_amount_by_person_top10(_filter_recode)
        res = self.query(_filter_amount, self.business_area_collection)
        return res

    def spe_statistics_education_income_quantity(self,condition, page, count):
        '''服务人员-统计-服务收入by 学历'''
        _filter = self.__get_all_service_person_all()
        _filter_education = self.__filter_education(_filter)
        _filter_recode = self.__get_service_recode_by_servicer(_filter_education)
        _filter_amount = self.__group_amount_by_edution(_filter_recode)
        res = self.query(_filter_amount, self.business_area_collection)
        return res
        
    def spe_statistics_age_income_quantity(self,condition, page, count):
        '''服务人员-统计-服务收入by 年龄 '''
        _filter = self.__get_all_service_person_all()
        _filter_age = self.__worker_group_by_age(_filter)
        _filter_recode = self.__get_service_recode_by_servicer(_filter_age)
        _filter_amount = self.__group_amount_by_age(_filter_recode)
        res = self.query(_filter_amount, self.business_area_collection)
        return res

    def spe_statistics_sex_income_quantity(self,condition, page, count):
        '''服务人员-统计-服务收入by 性别 '''
        _filter = self.__get_all_service_person_all()
        _filter_recode = self.__get_service_recode_by_servicer(_filter)
        _filter_amount = self.__group_amount_by_sex(_filter_recode)
        res = self.query(_filter_amount, self.business_area_collection)
        return res

    

    #######公共部分 ########
    def __eld_area_basic(self):
        '''本行政区划内的60岁以上生存长者信息'''
        _filter = self.__org_area()
        _filter.unwind('user_info')\
                .match((C('user_info.personnel_type') == UserType.Personnel)
                     & (C('user_info.personnel_info.dead')==0)
                     & (C('user_info.personnel_info.personnel_category') == '长者'))\
               .add_fields({'birth_year': self.ao.year('$user_info.personnel_info.date_birth')})\
               .add_fields({'age': ((F('birth_year')-self.current_year)*(-1)).f})\
               .match(C('age') >60)
        return _filter
    def set_session_area(self):
        '''设置session的区域id'''
        account_id=get_current_account_id(self.session)
        _filter=MongoBillFilter()
        _filter.match_bill(C('account_id')==account_id)\
               .lookup_bill('PT_Administration_Division','admin_area_id','id','div_info')\
               .graph_lookup('PT_Administration_Division','$div_info.parent_id','parent_id','id','all_admin')\
               .unwind('all_admin')\
               .inner_join_bill('PT_Business_Area','all_admin.id','admin_id','area_info')
        res=self.query(_filter,'PT_User')
        self.session[SecurityConstant.area] = res[0]['area_info']['id']
        return res[0]['area_info']['id']

    def get_current_user_area_id(self):
        '''通过session获取当前登录用户的区域id'''
        if SecurityConstant.area in list(self.session.keys()):
            return self.session[SecurityConstant.area]
        else:
            res=self.set_session_area()
            return res

    def ___create_list(self, obj_list):
        '''将数据转成列表
        eg : obj_list = [{'y':a},{'y':b},{'y':c}] >> [a,b,c]
        '''
        new_list = []
        for obj in obj_list:
            tep = list(obj.values())
            new_list.append(tep[0])
        return new_list

    def __org_area(self):
        '''找到某业务区域内的所有user信息'''
        division_id=self.get_current_user_area_id()
        _filter = MongoBillFilter()
        _filter.match(C('id') == division_id)\
               .inner_join('PT_Administration_Division', 'admin_id', 'id', 'admin_info')\
               .graph_lookup('PT_Administration_Division', '$admin_info.parent_id', 'id', 'parent_id', 'all_admin')\
               .project({'admin_id': '$all_admin.id'})\
               .unwind('admin_id')\
               .inner_join_bill('PT_User', 'admin_id', 'admin_area_id', 'user_info')
        return _filter

    def __elder_group_by_age(self, _filter):
        _filter.add_fields({'age': ((F('year')-self.current_year)*(-1)).f})\
               .add_fields({'age_range': self.ao.switch([self.ao.case(((F('age') >= 50) & (F('age') < 60)), '50-59'),
                                                         self.ao.case(((F('age') >= 60) & (F('age') < 70)), '60-69'),
                                                         self.ao.case(((F('age') >= 70) & (F('age') < 80)), '70-79'),
                                                         self.ao.case(((F('age') >= 80) & (F('age') < 90)), '80-89'),
                                                         self.ao.case(((F('age') >= 90) & (F('age') < 100)), '90-99')], '100以上')})
        return _filter

    def __worker_group_by_age(self, _filter):
        _filter.add_fields({'age': ((F('year')-self.current_year)*(-1)).f})\
               .add_fields({'age_range': self.ao.switch([self.ao.case(((F('age') >= 20) & (F('age') < 30)), '20-29'),
                                                         self.ao.case(((F('age') >= 30) & (F('age') < 40)), '30-39'),
                                                         self.ao.case(((F('age') >= 40) & (F('age') < 50)), '40-49')], '50以上')})
        return _filter

    def _group_by_date(self, _filter,col_name,date_unit):
        '''按date进行分组统计时，对日期进行处理，处理后数据存为新的一列
        Args :
            col_name:待处理的日期列名
            date_unit：分组的日期粒度，三个值可选：日，周，月 [暂时仅支持日和月]
        '''
        if date_unit == '日':
            _filter.add_fields({'new_date': self.ao.date_to_string(col_name,'%Y-%m-%d')})
        elif date_unit == '月':
            _filter.add_fields({'new_date': self.ao.date_to_string(col_name,'%Y-%m')})
        return _filter

    def __get_all_service_person_all(self):
        '''获取业务区域下所有的服务人员'''
        _filter = self.__org_area()
        _filter.inner_join_bill('PT_User_Relationship', 'user_info.id', 'subordinate_relation_people', 'relation_info')\
               .inner_join_bill('PT_User_Relationship_Type', 'relation_info.relationship_type_id', 'id', 'relation_type_info')\
               .match((C('relation_type_info.name') == relactionship.worker.value))
        return _filter

    def __get_data(self,_filter,table_name,page=None,count=None):
        res = self.query(_filter,table_name)
        return res

    def __get_organization(self,condition):
        return condition['id']
    
    def __get_elder_filter(self,condition):
        '''获取某机构下长者的filter'''
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match_bill(C('organization_id') == oragnization_id)\
               .inner_join_bill('PT_Bed', 'id', 'area_id', 'bed')\
                .match_bill((C('bed.residents_id') != None) | (C('bed.residents_id') != ''))\
                .inner_join_bill('PT_User', 'bed.residents_id', 'id', 'user')\
                .project({'_id':0,'bed._id':0,'user._id':0})
        return _filter

    def __get_bed_filter(self,condition):
        '''获取某机构下所有床位'''
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match_bill(C('organization_id') == oragnization_id)\
               .inner_join_bill('PT_Bed', 'id', 'area_id', 'bed') 
                
        return _filter

    def __get_worker_filter(self,condition):
        '''获取该机构下的工作人员'''
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match(C('main_relation_people') == oragnization_id)\
        .inner_join('PT_User_Relationship_Type', 'relationship_type_id', 'id', 'relation_type_info')\
               .match_bill(C('relation_type_info.name') == relactionship.worker.value) \
               .inner_join_bill('PT_User', 'subordinate_relation_people', 'id', 'user')
        return _filter

    def __get_age_range(self):
        switch = self.ao.switch(
            [
                self.ao.case(((F('age') >= 50) & (F('age') < 60)), '50-59'),
                self.ao.case(((F('age') >= 60) & (F('age') < 70)), '60-69'),
                self.ao.case(((F('age') >= 70) & (F('age') < 80)),'70-79'),
                self.ao.case(((F('age') >= 80) & (F('age') < 90)), '80-89'),
                self.ao.case(((F('age') >= 90) & (F('age') < 100)), '90-99'),                        
            ]
            , '100以上')
        return switch
    
    def __get_organization_filter(self,condition):
        '''当前机构filter'''
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == oragnization_id)
        return _filter

    def __get_activity_filter(self,condition):
        '''该机构下的活动'''
        oragnization_id = self.__get_organization(condition)
        _filter = MongoBillFilter()
        _filter.match(C('organization') == oragnization_id)
        return _filter

    def ___org_area_community(self):
        '''获取指定业务区域内的社区机构'''
        _filter = self.__org_area()
        _filter.match(C('user_info.personnel_type') == UserType.Organizational)\
               .match(C('user_info.organization_info.personnel_category') == '幸福院')
        return _filter

    def __org_area_community_service_person(self):
        '''获取指定业务区域内的社区机构服务人员'''

        _filter = self.___org_area_community()
        _filter.inner_join_bill('PT_User_Relationship', 'user_info.id', 'main_relation_people', 'relation_info')\
               .inner_join_bill('PT_User_Relationship_Type', 'relation_info.relationship_type_id', 'id', 'relation_type_info')\
               .match(C('relation_type_info.name') == '雇佣') \
               .add_fields({'organization_info':'$user_info'})\
               .inner_join_bill('PT_User', 'relation_info.subordinate_relation_people', 'id', 'user_info') \
               .add_fields({'year': self.ao.year('$user_info.personnel_info.date_birth')})
        return _filter
    
    ################################## 公共部分 end #########################################

    ####################### 分组统计 start #######################################
    # def __group_by_item(self, _filter):
    #     _filter.
    def __group_by_education(self, _filter):
        '''按学历分组'''
        _filter.unwind('user_info.qualification_info')\
               .inner_join_bill('PT_Qualification_Type', 'user_info.qualification_info.qualification_type_id', 'id', 'qualification_type_info')\
               .match(C('qualification_type_info.name') == '学历证明')\
               .group({'x': '$user_info.qualification_info.name'}, [{'y': self.ao.summation(1)}])
        return _filter

    def __group_by_sex(self, _filter):
        '''按性别分组'''
        _filter.group({'x': '$user_info.personnel_info.sex'}, [{'y': self.ao.summation(1)}])
        return _filter

    def __group_by_age(self, _filter,worker=None):
        '''按年龄分组统计'''
        _filter_age = self.__worker_group_by_age(_filter) if worker else self.__fiter_age(_filter)
        _filter_age.group({'x': '$age_range'}, [{'y': self.ao.summation(1)}])\
                   .sort({'x':1})
        return _filter_age

    def __group_by_town(self, _filter):
        '''按街镇分组统计'''
        # _filter_new = self.__filter_twon(_filter)
        _filter.group({'x': '$user_info.town'}, [{'y' : self.ao.summation(1)}])
        return _filter                

    def __group_by_organization(self, _filter):
        '''按组织机构分组'''
        _filter.group({'x': '$organization_info.name'}, [{'y': self.ao.summation(1)}])
        return _filter

    ####################### 分组统计 end #######################################

    ######### 统计服务评分 start ##################
    def __get_score_all(self,_filter):
        _filter.add_fields({'avg_score': self.ao.avg('$record_info.comment_list.comment_score')})\
               .group({}, [{'y': self.ao.avg('$avg_score')}])
        return _filter

    def __get_service_score_top10_quantity(self, _filter):
        '''获取服务评分top10的对象'''
        _filter.add_fields({'avg_score': self.ao.avg('$record_info.appraise_list.score')})\
               .group({'id': '$user_info.id', 'x': '$user_info.name'},[{'y':self.ao.avg('$avg_score')}])\
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_score_top10_by_education(self, _filter):
        '''按学历统计服务评分'''
        _filter.add_fields({'avg_score': self.ao.avg('$record_info.appraise_list.score')})\
               .group({'x': '$user_info.qualification_info.name'},[{'y':self.ao.avg('$avg_score')}])\
               .project({'x': 1, 'y': 1})
        return _filter

    
    def __get_service_score_top10_by_sex(self, _filter):
        '''按性别统计服务评分'''
        _filter.add_fields({'avg_score': self.ao.avg('$record_info.appraise_list.score')})\
               .group({'x': '$user_info.personnel_info.sex'},[{'y':self.ao.avg('$avg_score')}])\
               .project({'x': 1, 'y': 1})
        return _filter
    
    def __get_service_score_top10_by_age(self, _filter):
        '''按年龄统计服务评分'''
        _filter.add_fields({'avg_score': self.ao.avg('$record_info.appraise_list.score')})\
               .group({'x': '$age_range'},[{'y':self.ao.avg('$avg_score')}])\
               .sort({'x':1})\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_score_top10_by_twon(self, _filter):
        '''按街镇统计服务分数'''
        _filter.add_fields({'avg_score': self.ao.avg('$record_info.appraise_list.score')})\
               .group({'x': '$town'}, [{'y': self.ao.avg('$avg_score')}]) \
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter

    ######### 统计服务评分 end ##################

    ######### 统计服务评价 start ##################
    def __get_service_evaluate_top10_by_twon(self, _filter):
        '''按街镇统计服务评价次数'''
        _filter.add_fields({'count': self.ao.size('$record_info.appraise_list.content')})\
               .group({'x': '$town'}, [{'y': self.ao.summation('$count')}]) \
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_evaluate_top10_by_type(self, _filter):
        '''按长者类型统计服务评价次数'''
        _filter.add_fields({'count': self.ao.size('$record_info.appraise_list.content')})\
               .group({'x': '$social_type.name'}, [{'y': self.ao.summation('$count')}]) \
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter
    
    def __get_evaluate_count_by_item(self, _filter):
        '''按项目统计服务评价次数'''
        _filter.add_fields({'count': self.ao.size('$record_info.appraise_list.content')})\
                .group({'x': '$item.name', 'id': '$item.id'}, [{'y': self.ao.summation('$count')}]) \
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_evaluate_count_all(self, _filter):
        _filter.add_fields({'count': self.ao.size('$record_info.appraise_list.content')})\
                .group(None, [{'y': self.ao.summation('$count')}])
        return _filter

    
    ######### 统计服务评价 end ####################


    ########################## 统计服务次数 start##################################
    def __get_count_all(self, _filter):
        _filter.group({}, [{'y': self.ao.summation(1)}])
        return _filter

    def __get_service_count_top10_quantity(self, _filter):
        '''按人员统计服务次数'''
        _filter.group({'id': '$user_info.id', 'x': '$user_info.name'},[{'y':self.ao.summation(1)}])\
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_count_by_education(self, _filter):
        '''按学历统计服务次数'''
        _filter.group({'x': '$user_info.qualification_info.name'},[{'y':self.ao.summation(1)}])\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_count_by_age(self, _filter):
        '''按年龄统计服务次数'''
        _filter.group({'x': '$age_range'},[{'y':self.ao.summation(1)}])\
                .sort({'x':1})\
                .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_count_by_sex(self, _filter):
        '''按性别统计服务次数'''
        _filter.add_fields({'avg_score': self.ao.avg('$record_info.comment_list.comment_score')})\
               .group({'x': '$user_info.personnel_info.sex'},[{'y':self.ao.summation(1)}])\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_score_top10_by_twon(self, _filter):
        '''按街镇统计服务次数'''
        _filter.group({'x': '$twon'}, [{'y': self.ao.summation(1)}]) \
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_count_top10_by_type(self, _filter):
        '''按长者类型统计服务次数'''
        _filter.group({'x': '$social_type.name'}, [{'y': self.ao.summation(1)}]) \
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter
    ########################## 统计服务次数 end ##################################
    
    ####################### 查询条件（过滤）start #######################################
    def __get_service_recode_by_organization(self, _filter):
        '''获取机构的服务记录'''
        _filter.inner_join_bill('PT_Service_Order', 'user_info.id', 'service_provider_id', 'order')
        _filter_recode = self.__get_recode_by_order(_filter)
        return _filter_recode

    def __get_service_recode_by_servicer(self, _filter):
        '''通过服务人员获取服务记录'''
        _filter.inner_join_bill('PT_Service_Record', 'user_info.id', 'servicer_id', 'record_info')
        return _filter

    def __get_elder_recode_by_order(self, _filter):
        '''获取长者的服务记录'''
        _filter.inner_join_bill('PT_Service_Order', 'user_info.id', 'purchaser_id', 'order')
        _filter_recode = self.__get_recode_by_order(_filter)
        return _filter_recode
    
    def __get_recode_by_order(self, _filter):
        '''通过服务订单查询服务人员的服务记录'''
        _filter.inner_join_bill('PT_Service_Record', 'order.id', 'order_id', 'record_info') \
                .inner_join_bill('PT_Service_Item','record_info.item_id','id','item')
        return _filter


    def __filter_twon(self, _filter):
        '''查询街镇'''
        _filter.inner_join_bill('PT_Administration_Division', 'user_info.town', 'id', 'town') \
                .add_fields({'twon_name': '$town.name'})
        return _filter

    def __filter_education(self, _filter):
        '''过滤有学历人员'''
        _filter.unwind('user_info.qualification_info')\
               .inner_join_bill('PT_Qualification_Type', 'user_info.qualification_info.qualification_type_id', 'id', 'qualification_type_info')\
               .match(C('qualification_type_info.name') == '学历证明')
        return _filter

    def __fiter_age(self, _filter):
        '''年龄段标识'''
        # _filter.add_fields({'birth_year': self.ao.year('$user_info.personnel_info.birth_date')})\
        #        .add_fields({'age': ((F('year')-self.current_year)*(-1)).f})\
        _filter.add_fields({'age_range': self.ao.switch([self.ao.case(((F('age') >= 50) & (F('age') < 60)), '50-59'),
                                                         self.ao.case(((F('age') >= 60) & (F('age') < 70)), '60-69'),
                                                         self.ao.case(((F('age') >= 70) & (F('age') < 80)), '70-79'),
                                                         self.ao.case(((F('age') >= 80) & (F('age') < 90)), '80-89'),
                                                         self.ao.case(((F('age') >= 90) & (F('age') < 100)), '90-99')], '100以上')})
        return _filter

    ####################### 查询条件（过滤）end #######################################

    ####################### 服务收入（费用）start #######################################
    def __group_amount_by_person_top10(self, _filter):
        '''按人员统计收入'''
        _filter.group({'x': '$user_info.name', 'id': '$user_info.id'}, [{'y': self.ao.summation('$record_info.valuation_amount')}])\
               .project({'x': 1, 'y': 1,'_id':0})
        return _filter

    def __group_amount_by_edution(self, _filter):
        '''根据学历分组获取收入对象'''
        _filter.group({'x': '$user_info.qualification_info.name'}, [{'y': self.ao.summation('$record_info.valuation_amount')}])\
               .project({'x': 1, 'y': 1})
        return _filter

    def __group_amount_by_age(self, _filter):
        '''按年龄统计收入'''
        _filter.group({'x': '$age_range'},[{'y': self.ao.summation('$record_info.valuation_amount')}])\
                .sort({'x':1})\
               .project({'x': 1, 'y': 1})
        return _filter

    def __group_amount_by_sex(self, _filter):
        '''按性别统计收入'''
        _filter.group({'x': '$user_info.personnel_info.sex'},[{'y': self.ao.summation('$record_info.valuation_amount')}])\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_amount_all(self, _filter):
        '''总收入'''
        _filter.group({}, [{'y': self.ao.summation('$record_info.valuation_amount')}])
        return _filter

    def __get_amount_by_item(self, _filter):
        '''按项目统计服务收入'''
        _filter.group({'x': '$item.name', 'id': '$item.id'}, [{'y': self.ao.summation('$record_info.valuation_amount')}]) \
                      .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_amount_top10_by_twon(self, _filter):
        '''按街镇统计服务收入'''
        _filter.group({'x': '$town'}, [{'y': self.ao.summation('$record_info.valuation_amount')}]) \
               .sort({'y': -1})\
               .limit(10)\
               .project({'x': 1, 'y': 1})
        return _filter

    def __get_service_amount_top10_by_type(self,_filter):
        '''按所属身份统计'''
        _filter.group({'x': '$social_type.name'}, [{'y': self.ao.summation('$record_info.valuation_amount')}]) \
                .sort({'y': -1})\
                .limit(10)\
                .project({'x': 1, 'y': 1})
        return _filter
    
    ####################### 服务收入（费用）start #######################################
    

        
        
        
        
    
    
    